<?php
/**
 * https://gitee.com/Mao02
 * http://www.mao02.win/
 * jay_fun 410136330@qq.com
 * Date: 2018/4/7 0007
 * Time: 下午 17:51
 */

namespace app\common\service;

/**
 * 树形操作
 * Class Tree
 * @package jay\Surport
 */
class Tree {
	/**
	 * 数组转树
	 * @param $array
	 * @param string $pk
	 * @param string $pkey
	 * @param string $skey
	 * @return array
	 */
	public function array2tree($array,$pk='id',$pkey='pid',$skey='child') {
		$list = [];
		$tree = [];
		foreach ($array as $item){
			$list[$item[$pk]] = $item;
		}
		foreach ($list as &$item){
			if (isset($list[$item[$pkey]])){
				$list[$item[$pkey]][$skey][] = &$item;
			}else{
				$tree[] = &$item;
			}
		}
		return $tree;
	}

	/**
	 * 树转列表
	 * @param $tree
	 * @param string $skey
	 * @return array
	 */
	public function tree2list($tree,$skey='child',$prefix='_pre',$level=0){
	    $array = [];
		foreach ($tree as $item){
			$item[$prefix] = str_repeat('　｜',$level).($level?'—':'');
			if (isset($item[$skey])){
				$child = $this->tree2list($item[$skey],$skey,$prefix,$level+1);
				unset($item[$skey]);
				$array[] = $item;
				$array = array_merge($array, $child);
			}else{
				$array[] = $item;
			}
		}
		return $array;
	}

	/**
	 * 数组转列表
	 * @param $array
	 * @param string $pk
	 * @param string $pkey
	 * @param string $skey
	 * @return array
	 */
	public function array2list($array,$pk='id',$pkey='pid',$skey='child'){
		$tree = $this->array2tree($array, $pk, $pkey, $skey);
		return $this->tree2list($tree, $skey);
	}
}